<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/12/2
 * Time: 14:25
 */

namespace app\api\controller;

use think\Db;

class Apilogin extends Base
{
    /**
     * 发送验证码
     * @return \think\response\Json|void
     * phone       填写的手机号
     * type        发送场景   1 账号密码注册   2 重置密码
     * types       传1  图形验证
     * yzm         图形验证码
     * ex          区号
     */
    public function getPhoneCode()
    {
        $params = input('');
        
        if(trim($params['phone'], ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        
        $userInfo = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
        if(!empty($userInfo) && isset($params['type']) && $params['type'] == 1) { //注册
            return json(['status' => 0, 'msg' => '该手机号已注册']);
        }
        if(empty($userInfo) && isset($params['type']) && $params['type'] == 2) { //找回密码
            return json(['status' => 0, 'msg' => '该账号不存在']);
        }
        
        // 图形验证码
        if(isset($params['types']) && $params['types'] == 1){
            $yzm  = input('yzm');
            $yzm_data = Db::table('up_phonecode')->where('phone',$params['phone'])->find();
            if($yzm_data['yzm'] != $yzm){
                return json(['status'=>22,'msg'=>'图形验证码错误']);
            }
            if($yzm_data['yzm_status'] != 1){
                return json(['status'=>22,'msg'=>'此图形验证码已使用，请重新获取']);
            }
            Db::table('up_phonecode')->where('phone',$params['phone'])->update(['yzm_status'=>2]);
        }
    
        // 判断不同场景下的发送次数
//        $startTime = strtotime(date('Y-m-d 00:00:00'));//当天的起始时间
//        $endTime = strtotime(date('Y-m-d 23:59:59'));//当天的结束时间
//        $where = [];
//        $where['phone'] = $params['phone'];
//        $where['yzm_type'] = $params['send_type'];
//        $where['time'] = ['between', [$startTime, $endTime]];
//        $num = Db::table('up_phonecode')->where($where)->count('id');
//        if($num >= 5) {
//            return json(['status' => 0, 'msg' => '今日获取次数已用完，明天再来吧～']);
//        }
        $china_phone = $params['phone'];
        if($userInfo && $userInfo['user_china'] != 86){
            $china_phone = '00' . $userInfo['user_china'] . $params['phone'];
        }
        if(isset($params['ex']) && $params['ex'] != '86'){
            $china_phone = '00' . $params['ex'] . $params['phone'];
        }
        $code = GetRandCode();//6位数验证码
        $sendres = YzxSms($code, $china_phone, '', 1);//发送验证码
//        $sendres = json_decode($sendres, true);
        if($sendres['code'] != 0) {//发送不成功
            return json(['status' => 0, 'msg' => $sendres['msg']]);
        } else {
            $data = [
                'phone' => $params['phone'],//发送的手机号
                'code' => $code,//验证码
                'time' => time(),//验证码发送的时间戳
                'date_time' => date('Y-m-d H:i:s'),//日期格式
//                'yzm_type' => $params['send_type']
            ];
            $res = Db::table('up_phonecode')->insert($data);
            if(!$res) {
                return json(['status' => 0, 'msg' => '数据库操作失败']);
            }
            return json(['status' => 200, 'msg' => $code]);
        }
    }
    
    /**
     * 图形验证码
     * phone   手机号
     */
    public function pictureyzm(){
        $phone = input('phone');
        header("content-type:image/png");
        $validateLength=4;
        $strToDraw="";
        $chars=[
            "0","1","2","3","4",
            "5","6","7","8","9",
            "a","b","c","d","e","f","g",
            "h","i","j","k","l","m","n",
            "o","p","q","r","s","t",
            "u","v","w","x","y","z",
            "A","B","C","D","E","F","G",
            "H","I","J","K","L","M","N",
            "O","P","Q","R","S","T",
            "U","V","W","X","Y","Z"
        ];
        $imgW=80;
        $imgH=25;
        $imgRes=imagecreate($imgW,$imgH);
        $imgColor=imagecolorallocate($imgRes,255,255,100);
        $color=imagecolorallocate($imgRes,0,0,0);
        for($i=0;$i<$validateLength;$i++){
            $rand=rand(0,9);
            $strToDraw=$strToDraw.$chars[$rand];
        }
        imagestring($imgRes,5,20,5,$strToDraw,$color);
        for($i=0;$i<100;$i++){
            imagesetpixel($imgRes,rand(0,$imgW),rand(0,$imgH),$color);
        }
        $where['phone'] = $phone;
        $res= Db::table('up_phonecode')->where($where)->find();
        if($res['id']!=''){ // 不等于空的时候
            $data['yzm'] = $strToDraw;
            $data['yzm_status'] = 1;
            
            Db::table('up_phonecode')->where($where)->update($data);
        }else{//等于空空
            $data['yzm'] = $strToDraw;
            $data['phone'] = $phone;
            Db::table('up_phonecode')->insert($data);
        }
        imagepng($imgRes);
        imagedestroy($imgRes);exit;
    }
    
    /**
     * 账号密码注册
     * @return \think\response\Json
     * phone     手机号
     * pwd       密码
     * code      验证码
     * country_code    区号
     */
    public function register(){
        $phone = trim(input('phone'), ' ');
        $pwd = trim(input('pwd'), ' ');
        $code = trim(input('code'), ' ');
        $user_china = trim(input('country_code'), ' ');
        if($phone == '') return json(['status' => 0, 'msg' => '请填写手机号']);
        if($code == '') return json(['status' => 0, 'msg' => '请填写验证码']);
        if($pwd == '') return json(['status' => 0, 'msg' => '请填写密码']);
        
        // 账号
        $exist = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(!empty($exist)){
            if($exist['user_status'] == 3){
                return json(['status' => 0, 'msg' => '该账号已被冻结，请联系管理员']);
            }
            if($exist['user_status'] == 4){
                return json(['status' => 0, 'msg' => '该账号已注销，请联系管理员']);
            }
            return json(['status' => 0, 'msg' => '该账号已注册']);
        }
        // 验证码
        $yzm = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        // 10分钟超时
        $now = time();
        if($now - $yzm['time'] >= 1801) return json(['status' => 0, 'msg' => '验证码失效']);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码已使用']);
        $str = substr($phone, -4);
        $insert = [
            'user_phone' => $phone,
            'user_create_id' => $this->getRandNum(),
            'user_time' => date('Y-m-d H:i:s'),
            'user_password' => md5($pwd),
            'user_china' => $user_china,
            'user_username' => 'iBoat ' . $str . '船长'
        ];
        $res = Db::table('up_u_user')->insert($insert);
        if($res){
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
            
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            $userInfo['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '注册失败']);
        }
    }
    
    /**
     * 账号密码登录
     * @return \think\response\Json
     * phone    手机号
     * pwd      密码
     */
    public function passwordLogin(){
        $phone = trim(input('phone'), ' ');
        $pwd = trim(input('pwd'), ' ');
        if($phone == '') return json(['status' => 0, 'msg' => '请填写手机号']);
        if($pwd == '') return json(['status' => 0, 'msg' => '请填写密码']);
        
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($user)) return json(['status' => 0, 'msg' => '该手机号尚未注册']);
        
        $password = md5($pwd);
        if(!empty($user) && $password != $user['user_password']) return json(['status' => 0, 'msg' => '密码错误']);
        if($user['user_status'] == 2){
            return json(['status' => 0, 'msg' => '账号已删除']);
        }
        if($user['user_status'] == 3){
            return json(['status' => 0, 'msg' => '账号已被冻结，请联系管理员']);
        }
        if($user['user_status'] == 4){
            return json(['status' => 0, 'msg' => '账号已注销，请联系管理员']);
        }
            
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_last_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        $res = Db::table('up_u_user')->where('user_phone', $phone)->update($data);
        if($res){
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            // todo:融云
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            $userInfo['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '登录失败']);
        }
    }
    
    /**
     * 手机号验证码登录/注册
     * @return \think\response\Json
     * phone    手机号
     * code     验证码
     */
    public function phoneLogin(){
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        $user_china = trim(input('country_code'), ' ');
        if($phone == '') return json(['status' => 0, 'msg' => '请填写手机号']);
        if($code == '') return json(['status' => 0, 'msg' => '请填写验证码']);
        
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(!empty($user)){
            if($user['user_status'] == 2){
                return json(['status' => 0, 'msg' => '账号已删除']);
            }
            if($user['user_status'] == 3){
                return json(['status' => 0, 'msg' => '账号已被冻结，请联系管理员']);
            }
            if($user['user_status'] == 4){
                return json(['status' => 0, 'msg' => '账号已注销，请联系管理员']);
            }
        }
        
        //=========验证验证码
        $yzm = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        // 10分钟超时
        $now = time();
        if($now - $yzm['time'] >= 1801) return json(['status' => 0, 'msg' => '验证码超时']);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码失效']);
        
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_last_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        if($user){ // 登录
            $result = Db::table('up_u_user')->where('user_phone', $phone)->update($data);
            if($result){
                $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
//                // 判断用户有没有设置密码,没有密码，跳转到设置密码页面
//                if(empty($userInfo['user_password'])){
//                    return json(['status' => 201, 'msg' => $userInfo]);
//                }
                //修改验证码状态
                Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
                $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
                $userInfo['rytoken'] = $rytoken['token'];
                return json(['status' => 200, 'msg' => $userInfo]);
            }else{
                return json(['status' => 0, 'msg' => '快捷登录失败']);
            }
        }else{
            $str = substr($phone, -4);
            $data['user_phone'] = $phone;
            $data['user_time'] = date('Y-m-d H:i:s');
            $data['user_create_id'] = $this->getRandNum();
            $data['user_china'] = $user_china;
            $data['user_username'] = 'iBoat ' . $str . '船长';
           
            $userid = Db::table('up_u_user')->insertGetId($data);
            if($userid){
                $userInfo = Db::table('up_u_user')->where('user_id', $userid)->find();
                //修改验证码状态
                Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
                // todo:融云
                $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
                $userInfo['rytoken'] = $rytoken['token'];
                return json(['status' => 200, 'msg' => $userInfo]);
            }else{
                return json(['status' => 0, 'msg' => '快捷登录失败']);
            }
        }
    }
    
    /**
     * 重置密码
     * @return \think\response\Json
     * phone     手机号
     * pwd       密码
     * code      验证码
     */
    public function resetPassword(){
        $phone = trim(input('phone'), ' ');
        $pwd = trim(input('pwd'), ' ');
        $code = trim(input('code'), ' ');
        if($phone == '') return json(['status' => 0, 'msg' => '请填写手机号']);
        if($code == '') return json(['status' => 0, 'msg' => '请填写验证码']);
        if($pwd == '') return json(['status' => 0, 'msg' => '请填写密码']);
        
        // 账号
        $exist = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($exist)) return json(['status' => 0, 'msg' => '该账号未注册']);
        // 验证码
        $yzm = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        // 10分钟超时
        $now = time();
        if($now - $yzm['time'] >= 1801) return json(['status' => 0, 'msg' => '验证码失效']);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码已使用']);
        $update = [
            'user_update_time' => date('Y-m-d H:i:s'),
            'user_password' => md5($pwd)
        ];
        $res = Db::table('up_u_user')->where('user_phone', $phone)->update($update);
        if($res){
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
            return json(['status' => 200, 'msg' => '重置成功']);
        }else{
            return json(['status' => 0, 'msg' => '重置失败']);
        }
    }
    
    /**
     * 第三方登录第一步
     * @return \think\response\Json
     * login_type      1 apple   2 微信   3 QQ
     * third_token     微信、QQ传token,apple传ID
     */
    public function thirdLogin(){
        $login_type = input('login_type'); // 1 apple   2 微信   3 QQ
        $third_token = input('third_token'); // 微信、QQ传token，apple传ID
        if($login_type == 1){
            $field = 'user_apple_token';
        }elseif($login_type == 2){
            $field = 'user_wx_token';
        }else{
            $field = 'user_qq_token';
        }
        $first_login = Db::table('up_u_user')->where($field, $third_token)->find();
        if($first_login){ // 有记录
            if($first_login['user_status'] == 2){
                return json(['status' => 0, 'msg' => '该账号已被删除']);
            }
            if($first_login['user_status'] == 3){
                return json(['status' => 0, 'msg' => '该账号已被冻结，请联系管理员']);
            }
            if($first_login['user_status'] == 4){
                return json(['status' => 0, 'msg' => '该账号已注销，请联系管理员']);
            }
            $token = md5(date('YmdHis') . rand(100000, 999999));
            $update = [
                'user_last_time' => date('Y-m-d H:i:s'),
                'user_token' => $token
            ];
            $res = Db::table('up_u_user')->where('user_id', $first_login['user_id'])->update($update);
            if($res){
                $userInfo = Db::table('up_u_user')->where('user_id', $first_login['user_id'])->find();
                // todo:融云
                $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
                $userInfo['rytoken'] = $rytoken['token'];
                return json(['status' => 200, 'msg' => $userInfo]);
            }else{
                return json(['status' => 0, 'msg' => '登录失败']);
            }
        }else{
            // 第一次登录，先绑定手机
            return json(['status' => 201, 'msg' => '']);
        }
    }
    
    /**
     * 第三方登录第二步
     * @return \think\response\Json
     * phone           手机号
     * code            验证码
     * login_type      登录方式  1 apple  2 微信  3 QQ
     * third_token     第三方token
     * third_nickname  第三方昵称，apple传空
     * third_image     第三方头像，apple传空
     * country_code    国家区号
     */
    public function thirdLoginS(){
        $phone = input('phone');
        $code = input('code');
        $login_type = input('login_type');
        $third_token = input('third_token');
        $third_nickname = input('third_nickname');
        $third_image = input('third_image');
        $user_china = input('country_code');
        if($login_type == 1){
            $field = 'user_apple_token';
        }elseif($login_type == 2){
            $field = 'user_wx_token';
        }else{
            $field = 'user_qq_token';
        }
        
        if($phone == '') return json(['status' => 0, 'msg' => '请填写手机号']);
        if($code == '') return json(['status' => 0, 'msg' => '请填写验证码']);
        //=========验证验证码
        $yzm = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        // 10分钟超时
        $now = time();
        if($now - $yzm['time'] >= 1801) return json(['status' => 0, 'msg' => '验证码超时']);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码失效']);
        
        $have = Db::table('up_u_user')->where('user_phone', $phone)->find();
        $token = md5(date('YmdHis') . rand(100000, 999999));
        if($have){ // 绑定已存在的手机号
            if($have['user_status'] == 2){
                return json(['status' => 0, 'msg' => '该账号已被删除']);
            }
            if($have['user_status'] == 3){
                return json(['status' => 0, 'msg' => '该账号已被冻结，请联系管理员']);
            }
            if($have['user_status'] == 4){
                return json(['status' => 0, 'msg' => '该账号已注销，请联系管理员']);
            }
            $update = [
                'user_token' => $token,
                'user_last_time' => date('Y-m-d H:i:s'),
                $field => $third_token
            ];
            if($login_type == 2){
                $update['user_wx_img'] = $third_image;
                $update['user_wx_nickname'] = $third_nickname;
            }
            if($login_type == 3){
                $update['user_qq_img'] = $third_image;
                $update['user_qq_nickname'] = $third_nickname;
            }
            if(empty($have['user_username'])) $update['user_username'] = $third_nickname;
            if(empty($have['user_image'])) $update['user_image'] = $third_image;
            $res = Db::table('up_u_user')->where('user_phone', $phone)->update($update);
        }else{
            $insert = [
                'user_phone' => $phone,
                'user_token' => $token,
                'user_create_id' => $this->getRandNum(),
                $field => $third_token,
                'user_time' => date('Y-m-d H:i:s'),
                'user_last_time' => date('Y-m-d H:i:s'),
                'user_china' => $user_china
            ];
            if($login_type == 2){
                $insert['user_wx_img'] = $third_image;
                $insert['user_wx_nickname'] = $third_nickname;
                $insert['user_image'] = $third_image;
                $insert['user_username'] = $third_nickname;
            }
            if($login_type == 3){
                $insert['user_qq_img'] = $third_image;
                $insert['user_qq_nickname'] = $third_nickname;
                $insert['user_image'] = $third_image;
                $insert['user_username'] = $third_nickname;
            }
            $res = Db::table('up_u_user')->insert($insert);
        }
        if($res){
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            // todo:融云
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            $userInfo['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '登录异常']);
        }
    }
    
    /**
     * 用户服务协议
     * @return \think\response\Json
     */
    public function user_agreement(){
        $agreement = Db::table('up_other')->where('other_id', 1)->value('other_user_agreement');
        if($agreement){
            return json(['status' => 200, 'msg' => $agreement]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 用户隐私协议
     * @return \think\response\Json
     */
    public function user_ys(){
        $ys = Db::table('up_other')->where('other_id', 2)->value('other_ys_agreement');
        if($ys){
            return json(['status' => 200, 'msg' => $ys]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 国际区号
     * @return \think\response\Json
     * keyword    搜索关键词
     */
    public function countryCode(){
        $keyword = input('keyword');
        $where = [];
        if(isset($keyword) && $keyword != ''){
            $where['country_name'] = ['like', '%' . $keyword . '%'];
        }
        $code = Db::table('up_country_code')
            ->field('country_id, country_name, country_code')
            ->where($where)
            ->select();
        return json(['status' => 200, 'msg' => $code]);
    }
    
    /**
     * 获取省市区的三维数组
     * @return \think\response\Json
     */
    public function getArea()
    {
        $provinceLists = Db::name('area')->where('level', 1)->select(); // 省
        $cityLists = Db::name('area')->where('level', 2)->select(); // 市
        $districtLists = Db::name('area')->where('level', 3)->select(); // 区
        foreach($cityLists as $k => $city) {
            foreach($districtLists as $kk => $district) {
                if($city['district_id'] == $district['pid']) {
                    $cityLists[$k]['qu'][] = $district;
                }
            }
        }
        foreach($provinceLists as $key => $province) {
            foreach($cityLists as $ke => $city) {
                if($province['district_id'] == $city['pid']) {
                    $provinceLists[$key]['city'][] = $city;
                }
            }
        }
        return json(['status' => 200, 'msg' => $provinceLists]);
    }
}